package result

import (
	"encoding/json"
	"net/http"
)

const (
	SuccessCode = 200
	FailCode    = 500
	SuccessMsg  = "成功"
	FailMsg     = "失败"
)

const (
	ParamsErr   = "参数解析错误"
	Transaction = "触发事务撤销"
	Del         = false
)

type Res struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// Ok 成功返回数据
func Ok(w http.ResponseWriter, r *http.Request, data interface{}) {
	var result = Res{
		Code:    SuccessCode,
		Message: SuccessMsg,
		Data:    data,
	}
	handleData(w, r, &result)
}

// Fail 失败返回数据
func Fail(w http.ResponseWriter, r *http.Request, err error) {
	var result = Res{
		Code:    FailCode,
		Message: err.Error(),
		Data:    nil,
	}
	handleData(w, r, &result)
}

// Custom 自定义返回数据
func Custom(w http.ResponseWriter, r *http.Request, result *Res) {
	handleData(w, r, result)
}

func handleData(w http.ResponseWriter, r *http.Request, data *Res) {
	setupCORS(&w)
	w.Header().Set("Content-Type", "application/json")
	bytes, err := json.Marshal(data)
	if err != nil {
		s := err.Error()
		var errBytes = []byte("服务器错误：" + s)
		_, err := w.Write(errBytes)
		if err != nil {
			return
		}
	}
	_, err = w.Write(bytes)

}

func setupCORS(w *http.ResponseWriter) {
	(*w).Header().Set("Access-Control-Allow-Origin", "*")
	(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
